<?php
namespace app\common\audit\logic;

use app\common\audit\model\AuditFlow;
use app\common\audit\model\AuditResult;
use app\common\BaseLogic;
use think\db\exception\DbException;
use think\Exception;

class AuditResultLogic extends BaseLogic
{
    public function getAuditRs($auditNo) {
        $model = new AuditResult();
        return $model->where('audit_no', $auditNo)->find();
    }

    /**
     * @param $master 条件数据
     * @param $user 提交者
     * @param array $source 要审核的数据映射，要使用class名称
     * @param array $options , timing=审核类型|company_id=目标审核公司 一些修正选项
     * @return string
     * @throws Exception
     * @throws DbException
     */
    public function initAudit(&$master, &$user, &$source=[], $options)
    {
        $processLogic = new AuditProcessLogic();
        $process = $processLogic->getAuditProcess($master, $user, $options);
        if (empty($process)) throw new Exception("未设置审核流程");

        try {
            list($audit, $operator) = $processLogic->getNextAudit($process, $user);
        } catch (Exception $e) {
            throw $e;
        }

        // 创建审核流程
        try {
            $data['audit_no'] = date('YmdHis') . uniqid();
            $data['module'] = 'order';
            $data['audit_type'] = $options['timing'];
            $data['company_id'] = $options['company_id'];
            $data['create_user_id'] = $user['id'];
            $data['master_id'] = $master['id'];
            $data['status'] = 0;
            $data['source'] = $source;
            $data['process'] = $process;

            $model = new AuditResult();
            $model->save($data);
        } catch (DbException $e) {
            throw $e;
        }

        // 创建子审核流程
        try {
            $data = [];
            $data['audit_id'] = $model->id;
            $data['audit_no'] = $model->audit_no;
            $data['operate_user_id'] = $user['id'];
            $data['audit_user_id'] = $operator['id'];
            $data['audit_item_id'] = $audit['id'];

            $subModel = new AuditFlow();
            $subModel->save($data);
        } catch (DbException $e) {
            throw $e;
        }

        return $model->audit_no;
    }
}